<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Executing JavaScript | Node.js v6.9.1 Documentation</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic">
  <link rel="stylesheet" href="assets/style.css">
  <link rel="stylesheet" href="assets/sh.css">
  <link rel="canonical" href="https://nodejs.org/api/vm.html">
</head>
<body class="alt apidoc" id="api-section-vm">
  <div id="content" class="clearfix">
    <div id="column2" class="interior">
      <div id="intro" class="interior">
        <a href="/" title="Go back to the home page">
          Node.js
        </a>
      </div>
      <ul>
<li><a class="nav-documentation" href="documentation.html">About these Docs</a></li>
<li><a class="nav-synopsis" href="synopsis.html">Usage &amp; Example</a></li>
</ul>
<div class="line"></div>

<ul>
<li><a class="nav-assert" href="assert.html">Assertion Testing</a></li>
<li><a class="nav-buffer" href="buffer.html">Buffer</a></li>
<li><a class="nav-addons" href="addons.html">C/C++ Addons</a></li>
<li><a class="nav-child_process" href="child_process.html">Child Processes</a></li>
<li><a class="nav-cluster" href="cluster.html">Cluster</a></li>
<li><a class="nav-cli" href="cli.html">Command Line Options</a></li>
<li><a class="nav-console" href="console.html">Console</a></li>
<li><a class="nav-crypto" href="crypto.html">Crypto</a></li>
<li><a class="nav-debugger" href="debugger.html">Debugger</a></li>
<li><a class="nav-dns" href="dns.html">DNS</a></li>
<li><a class="nav-domain" href="domain.html">Domain</a></li>
<li><a class="nav-errors" href="errors.html">Errors</a></li>
<li><a class="nav-events" href="events.html">Events</a></li>
<li><a class="nav-fs" href="fs.html">File System</a></li>
<li><a class="nav-globals" href="globals.html">Globals</a></li>
<li><a class="nav-http" href="http.html">HTTP</a></li>
<li><a class="nav-https" href="https.html">HTTPS</a></li>
<li><a class="nav-modules" href="modules.html">Modules</a></li>
<li><a class="nav-net" href="net.html">Net</a></li>
<li><a class="nav-os" href="os.html">OS</a></li>
<li><a class="nav-path" href="path.html">Path</a></li>
<li><a class="nav-process" href="process.html">Process</a></li>
<li><a class="nav-punycode" href="punycode.html">Punycode</a></li>
<li><a class="nav-querystring" href="querystring.html">Query Strings</a></li>
<li><a class="nav-readline" href="readline.html">Readline</a></li>
<li><a class="nav-repl" href="repl.html">REPL</a></li>
<li><a class="nav-stream" href="stream.html">Stream</a></li>
<li><a class="nav-string_decoder" href="string_decoder.html">String Decoder</a></li>
<li><a class="nav-timers" href="timers.html">Timers</a></li>
<li><a class="nav-tls" href="tls.html">TLS/SSL</a></li>
<li><a class="nav-tty" href="tty.html">TTY</a></li>
<li><a class="nav-dgram" href="dgram.html">UDP/Datagram</a></li>
<li><a class="nav-url" href="url.html">URL</a></li>
<li><a class="nav-util" href="util.html">Utilities</a></li>
<li><a class="nav-v8" href="v8.html">V8</a></li>
<li><a class="nav-vm active" href="vm.html">VM</a></li>
<li><a class="nav-zlib" href="zlib.html">ZLIB</a></li>
</ul>
<div class="line"></div>

<ul>
<li><a class="nav-https-github-com-nodejs-node" href="https://github.com/nodejs/node">GitHub Repo &amp; Issue Tracker</a></li>
<li><a class="nav-http-groups-google-com-group-nodejs" href="http://groups.google.com/group/nodejs">Mailing List</a></li>
</ul>

    </div>

    <div id="column1" data-id="vm" class="interior">
      <header>
        <h1>Node.js v6.9.1 Documentation</h1>
        <div id="gtoc">
          <p>
            <a href="index.html" name="toc">Index</a> |
            <a href="all.html">View on single page</a> |
            <a href="vm.json">View as JSON</a>
          </p>
        </div>
        <hr>
      </header>

      <div id="toc">
        <h2>Table of Contents</h2>
        <ul>
<li><a href="#vm_executing_javascript">Executing JavaScript</a><ul>
<li><a href="#vm_class_vm_script">Class: vm.Script</a><ul>
<li><a href="#vm_new_vm_script_code_options">new vm.Script(code, options)</a></li>
<li><a href="#vm_script_runincontext_contextifiedsandbox_options">script.runInContext(contextifiedSandbox[, options])</a></li>
<li><a href="#vm_script_runinnewcontext_sandbox_options">script.runInNewContext([sandbox][, options])</a></li>
<li><a href="#vm_script_runinthiscontext_options">script.runInThisContext([options])</a></li>
</ul>
</li>
<li><a href="#vm_vm_createcontext_sandbox">vm.createContext([sandbox])</a></li>
<li><a href="#vm_vm_iscontext_sandbox">vm.isContext(sandbox)</a></li>
<li><a href="#vm_vm_runincontext_code_contextifiedsandbox_options">vm.runInContext(code, contextifiedSandbox[, options])</a></li>
<li><a href="#vm_vm_runindebugcontext_code">vm.runInDebugContext(code)</a></li>
<li><a href="#vm_vm_runinnewcontext_code_sandbox_options">vm.runInNewContext(code[, sandbox][, options])</a></li>
<li><a href="#vm_vm_runinthiscontext_code_options">vm.runInThisContext(code[, options])</a></li>
<li><a href="#vm_example_running_an_http_server_within_a_vm">Example: Running an HTTP Server within a VM</a></li>
<li><a href="#vm_what_does_it_mean_to_contextify_an_object">What does it mean to &quot;contextify&quot; an object?</a></li>
</ul>
</li>
</ul>

      </div>

      <div id="apicontent">
        <h1>Executing JavaScript<span><a class="mark" href="#vm_executing_javascript" id="vm_executing_javascript">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><!--name=vm-->
<p>The <code>vm</code> module provides APIs for compiling and running code within V8 Virtual
Machine contexts. It can be accessed using:</p>
<pre><code class="lang-js">const vm = require(&#39;vm&#39;);
</code></pre>
<p>JavaScript code can be compiled and run immediately or compiled, saved, and run
later.</p>
<h2>Class: vm.Script<span><a class="mark" href="#vm_class_vm_script" id="vm_class_vm_script">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><p>Instances of the <code>vm.Script</code> class contain precompiled scripts that can be
executed in specific sandboxes (or &quot;contexts&quot;).</p>
<h3>new vm.Script(code, options)<span><a class="mark" href="#vm_new_vm_script_code_options" id="vm_new_vm_script_code_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><ul>
<li><code>code</code> <span class="type">&lt;string&gt;</span> The JavaScript code to compile.</li>
<li><code>options</code><ul>
<li><code>filename</code> <span class="type">&lt;string&gt;</span> Specifies the filename used in stack traces produced
by this script.</li>
<li><code>lineOffset</code> <span class="type">&lt;number&gt;</span> Specifies the line number offset that is displayed
in stack traces produced by this script.</li>
<li><code>columnOffset</code> <span class="type">&lt;number&gt;</span> Specifies the column number offset that is displayed
in stack traces produced by this script.</li>
<li><code>displayErrors</code> <span class="type">&lt;boolean&gt;</span> When <code>true</code>, if an <a href="errors.html#errors_class_error"><code>Error</code></a> error occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace.</li>
<li><code>timeout</code> <span class="type">&lt;number&gt;</span> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a>
will be thrown.</li>
<li><code>cachedData</code> <a href="buffer.html#buffer_class_buffer" class="type">&lt;Buffer&gt;</a> Provides an optional <code>Buffer</code> with V8&#39;s code cache
data for the supplied source. When supplied, the <code>cachedDataRejected</code> value
will be set to either <code>true</code> or <code>false</code> depending on acceptance of the data
by V8.</li>
<li><code>produceCachedData</code> <span class="type">&lt;boolean&gt;</span> When <code>true</code> and no <code>cachedData</code> is present, V8
will attempt to produce code cache data for <code>code</code>. Upon success, a
<code>Buffer</code> with V8&#39;s code cache data will be produced and stored in the
<code>cachedData</code> property of the returned <code>vm.Script</code> instance.
The <code>cachedDataProduced</code> value will be set to either <code>true</code> or <code>false</code>
depending on whether code cache data is produced successfully.</li>
</ul>
</li>
</ul>
<p>Creating a new <code>vm.Script</code> object compiles <code>code</code> but does not run it. The
compiled <code>vm.Script</code> can be run later multiple times. It is important to note
that the <code>code</code> is not bound to any global object; rather, it is bound before
each run, just for that run.</p>
<h3>script.runInContext(contextifiedSandbox[, options])<span><a class="mark" href="#vm_script_runincontext_contextifiedsandbox_options" id="vm_script_runincontext_contextifiedsandbox_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><ul>
<li><code>contextifiedSandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&lt;Object&gt;</a> A <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object as returned by the
<code>vm.createContext()</code> method.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&lt;Object&gt;</a><ul>
<li><code>filename</code> <span class="type">&lt;string&gt;</span> Specifies the filename used in stack traces produced
by this script.</li>
<li><code>lineOffset</code> <span class="type">&lt;number&gt;</span> Specifies the line number offset that is displayed
in stack traces produced by this script.</li>
<li><code>columnOffset</code> <span class="type">&lt;number&gt;</span> Specifies the column number offset that is displayed
in stack traces produced by this script.</li>
<li><code>displayErrors</code> <span class="type">&lt;boolean&gt;</span> When <code>true</code>, if an <a href="errors.html#errors_class_error"><code>Error</code></a> error occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace.</li>
<li><code>timeout</code> <span class="type">&lt;number&gt;</span> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a>
will be thrown.</li>
<li><code>breakOnSigint</code>: if <code>true</code>, the execution will be terminated when
<code>SIGINT</code> (Ctrl+C) is received. Existing handlers for the
event that have been attached via <code>process.on(&quot;SIGINT&quot;)</code> will be disabled
during script execution, but will continue to work after that.
If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li>
</ul>
</li>
</ul>
<p>Runs the compiled code contained by the <code>vm.Script</code> object within the given
<code>contextifiedSandbox</code> and returns the result. Running code does not have access
to local scope.</p>
<p>The following example compiles code that increments a global variable, sets
the value of another global variable, then execute the code multiple times.
The globals are contained in the <code>sandbox</code> object.</p>
<pre><code class="lang-js">const util = require(&#39;util&#39;);
const vm = require(&#39;vm&#39;);

const sandbox = {
  animal: &#39;cat&#39;,
  count: 2
};

const script = new vm.Script(&#39;count += 1; name = &quot;kitty&quot;;&#39;);

const context = new vm.createContext(sandbox);
for (var i = 0; i &lt; 10; ++i) {
  script.runInContext(context);
}

console.log(util.inspect(sandbox));

// { animal: &#39;cat&#39;, count: 12, name: &#39;kitty&#39; }
</code></pre>
<h3>script.runInNewContext([sandbox][, options])<span><a class="mark" href="#vm_script_runinnewcontext_sandbox_options" id="vm_script_runinnewcontext_sandbox_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><ul>
<li><code>sandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&lt;Object&gt;</a> An object that will be <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a>. If <code>undefined</code>, a
new object will be created.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&lt;Object&gt;</a><ul>
<li><code>filename</code> <span class="type">&lt;string&gt;</span> Specifies the filename used in stack traces produced
by this script.</li>
<li><code>lineOffset</code> <span class="type">&lt;number&gt;</span> Specifies the line number offset that is displayed
in stack traces produced by this script.</li>
<li><code>columnOffset</code> <span class="type">&lt;number&gt;</span> Specifies the column number offset that is displayed
in stack traces produced by this script.</li>
<li><code>displayErrors</code> <span class="type">&lt;boolean&gt;</span> When <code>true</code>, if an <a href="errors.html#errors_class_error"><code>Error</code></a> error occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace.</li>
<li><code>timeout</code> <span class="type">&lt;number&gt;</span> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a>
will be thrown.</li>
</ul>
</li>
</ul>
<p>First contextifies the given <code>sandbox</code>, runs the compiled code contained by
the <code>vm.Script</code> object within the created sandbox, and returns the result.
Running code does not have access to local scope.</p>
<p>The following example compiles code that sets a global variable, then executes
the code multiple times in different contexts. The globals are set on and
contained within each individual <code>sandbox</code>.</p>
<pre><code class="lang-js">const util = require(&#39;util&#39;);
const vm = require(&#39;vm&#39;);

const script = new vm.Script(&#39;globalVar = &quot;set&quot;&#39;);

const sandboxes = [{}, {}, {}];
sandboxes.forEach((sandbox) =&gt; {
  script.runInNewContext(sandbox);
});

console.log(util.inspect(sandboxes));

// [{ globalVar: &#39;set&#39; }, { globalVar: &#39;set&#39; }, { globalVar: &#39;set&#39; }]
</code></pre>
<h3>script.runInThisContext([options])<span><a class="mark" href="#vm_script_runinthiscontext_options" id="vm_script_runinthiscontext_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&lt;Object&gt;</a><ul>
<li><code>filename</code> <span class="type">&lt;string&gt;</span> Specifies the filename used in stack traces produced
by this script.</li>
<li><code>lineOffset</code> <span class="type">&lt;number&gt;</span> Specifies the line number offset that is displayed
in stack traces produced by this script.</li>
<li><code>columnOffset</code> <span class="type">&lt;number&gt;</span> Specifies the column number offset that is displayed
in stack traces produced by this script.</li>
<li><code>displayErrors</code> <span class="type">&lt;boolean&gt;</span> When <code>true</code>, if an <a href="errors.html#errors_class_error"><code>Error</code></a> error occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace.</li>
<li><code>timeout</code> <span class="type">&lt;number&gt;</span> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a>
will be thrown.</li>
</ul>
</li>
</ul>
<p>Runs the compiled code contained by the <code>vm.Script</code> within the context of the
current <code>global</code> object. Running code does not have access to local scope, but
<em>does</em> have access to the current <code>global</code> object.</p>
<p>The following example compiles code that increments a <code>global</code> variable then
executes that code multiple times:</p>
<pre><code class="lang-js">const vm = require(&#39;vm&#39;);

global.globalVar = 0;

const script = new vm.Script(&#39;globalVar += 1&#39;, { filename: &#39;myfile.vm&#39; });

for (var i = 0; i &lt; 1000; ++i) {
  script.runInThisContext();
}

console.log(globalVar);

// 1000
</code></pre>
<h2>vm.createContext([sandbox])<span><a class="mark" href="#vm_vm_createcontext_sandbox" id="vm_vm_createcontext_sandbox">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><ul>
<li><code>sandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&lt;Object&gt;</a></li>
</ul>
<p>If given a <code>sandbox</code> object, the <code>vm.createContext()</code> method will <a href="#vm_what_does_it_mean_to_contextify_an_object">prepare
that sandbox</a> so that it can be used in calls to
<a href="#vm_vm_runincontext_code_contextifiedsandbox_options"><code>vm.runInContext()</code></a> or <a href="#vm_script_runincontext_contextifiedsandbox_options"><code>script.runInContext()</code></a>. Inside such scripts,
the <code>sandbox</code> object will be the global object, retaining all of its existing
properties but also having the built-in objects and functions any standard
<a href="https://es5.github.io/#x15.1">global object</a> has. Outside of scripts run by the vm module, <code>sandbox</code> will
remain unchanged.</p>
<p>If <code>sandbox</code> is omitted (or passed explicitly as <code>undefined</code>), a new, empty
<a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> sandbox object will be returned.</p>
<p>The <code>vm.createContext()</code> method is primarily useful for creating a single
sandbox that can be used to run multiple scripts. For instance, if emulating a
web browser, the method can be used to create a single sandbox representing a
window&#39;s global object, then run all <code>&lt;script&gt;</code> tags together within the context
of that sandbox.</p>
<h2>vm.isContext(sandbox)<span><a class="mark" href="#vm_vm_iscontext_sandbox" id="vm_vm_iscontext_sandbox">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.7</span>
</div><ul>
<li><code>sandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&lt;Object&gt;</a></li>
</ul>
<p>Returns <code>true</code> if the given <code>sandbox</code> object has been <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> using
<a href="#vm_vm_createcontext_sandbox"><code>vm.createContext()</code></a>.</p>
<h2>vm.runInContext(code, contextifiedSandbox[, options])<span><a class="mark" href="#vm_vm_runincontext_code_contextifiedsandbox_options" id="vm_vm_runincontext_code_contextifiedsandbox_options">#</a></span></h2>
<div class="signature"><ul>
<li><code>code</code> <span class="type">&lt;string&gt;</span> The JavaScript code to compile and run.</li>
<li><code>contextifiedSandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&lt;Object&gt;</a> The <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object that will be used
as the <code>global</code> when the <code>code</code> is compiled and run.</li>
<li><code>options</code><ul>
<li><code>filename</code> <span class="type">&lt;string&gt;</span> Specifies the filename used in stack traces produced
by this script.</li>
<li><code>lineOffset</code> <span class="type">&lt;number&gt;</span> Specifies the line number offset that is displayed
in stack traces produced by this script.</li>
<li><code>columnOffset</code> <span class="type">&lt;number&gt;</span> Specifies the column number offset that is displayed
in stack traces produced by this script.</li>
<li><code>displayErrors</code> <span class="type">&lt;boolean&gt;</span> When <code>true</code>, if an <a href="errors.html#errors_class_error"><code>Error</code></a> error occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace.</li>
<li><code>timeout</code> <span class="type">&lt;number&gt;</span> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a>
will be thrown.</li>
</ul>
</li>
</ul>
</div><p>The <code>vm.runInContext()</code> method compiles <code>code</code>, runs it within the context of
the <code>contextifiedSandbox</code>, then returns the result. Running code does not have
access to the local scope. The <code>contextifiedSandbox</code> object <em>must</em> have been
previously <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> using the <a href="#vm_vm_createcontext_sandbox"><code>vm.createContext()</code></a> method.</p>
<p>The following example compiles and executes different scripts using a single
<a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object:</p>
<pre><code class="lang-js">const util = require(&#39;util&#39;);
const vm = require(&#39;vm&#39;);

const sandbox = { globalVar: 1 };
vm.createContext(sandbox);

for (var i = 0; i &lt; 10; ++i) {
  vm.runInContext(&#39;globalVar *= 2;&#39;, sandbox);
}
console.log(util.inspect(sandbox));

// { globalVar: 1024 }
</code></pre>
<h2>vm.runInDebugContext(code)<span><a class="mark" href="#vm_vm_runindebugcontext_code" id="vm_vm_runindebugcontext_code">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><ul>
<li><code>code</code> <span class="type">&lt;string&gt;</span> The JavaScript code to compile and run.</li>
</ul>
<p>The <code>vm.runInDebugContext()</code> method compiles and executes <code>code</code> inside the V8
debug context. The primary use case is to gain access to the V8 <code>Debug</code> object:</p>
<pre><code class="lang-js">const vm = require(&#39;vm&#39;);
const Debug = vm.runInDebugContext(&#39;Debug&#39;);
console.log(Debug.findScript(process.emit).name);  // &#39;events.js&#39;
console.log(Debug.findScript(process.exit).name);  // &#39;internal/process.js&#39;
</code></pre>
<p><em>Note</em>: The debug context and object are intrinsically tied to V8&#39;s debugger
implementation and may change (or even be removed) without prior warning.</p>
<p>The <code>Debug</code> object can also be made available using the V8-specific
<code>--expose_debug_as=</code> [command line option][cli.md].</p>
<h2>vm.runInNewContext(code[, sandbox][, options])<span><a class="mark" href="#vm_vm_runinnewcontext_code_sandbox_options" id="vm_vm_runinnewcontext_code_sandbox_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><ul>
<li><code>code</code> <span class="type">&lt;string&gt;</span> The JavaScript code to compile and run.</li>
<li><code>sandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&lt;Object&gt;</a> An object that will be <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a>. If <code>undefined</code>, a
new object will be created.</li>
<li><code>options</code><ul>
<li><code>filename</code> <span class="type">&lt;string&gt;</span> Specifies the filename used in stack traces produced
by this script.</li>
<li><code>lineOffset</code> <span class="type">&lt;number&gt;</span> Specifies the line number offset that is displayed
in stack traces produced by this script.</li>
<li><code>columnOffset</code> <span class="type">&lt;number&gt;</span> Specifies the column number offset that is displayed
in stack traces produced by this script.</li>
<li><code>displayErrors</code> <span class="type">&lt;boolean&gt;</span> When <code>true</code>, if an <a href="errors.html#errors_class_error"><code>Error</code></a> error occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace.</li>
<li><code>timeout</code> <span class="type">&lt;number&gt;</span> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a>
will be thrown.</li>
</ul>
</li>
</ul>
<p>The <code>vm.runInNewContext()</code> first contextifies the given <code>sandbox</code> object (or
creates a new <code>sandbox</code> if passed as <code>undefined</code>), compiles the <code>code</code>, runs it
within the context of the created context, then returns the result. Running code
does not have access to the local scope.</p>
<p>The following example compiles and executes code that increments a global
variable and sets a new one. These globals are contained in the <code>sandbox</code>.</p>
<pre><code class="lang-js">const util = require(&#39;util&#39;);
const vm = require(&#39;vm&#39;);

const sandbox = {
  animal: &#39;cat&#39;,
  count: 2
};

vm.runInNewContext(&#39;count += 1; name = &quot;kitty&quot;&#39;, sandbox);
console.log(util.inspect(sandbox));

// { animal: &#39;cat&#39;, count: 3, name: &#39;kitty&#39; }
</code></pre>
<h2>vm.runInThisContext(code[, options])<span><a class="mark" href="#vm_vm_runinthiscontext_code_options" id="vm_vm_runinthiscontext_code_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><ul>
<li><code>code</code> <span class="type">&lt;string&gt;</span> The JavaScript code to compile and run.</li>
<li><code>options</code><ul>
<li><code>filename</code> <span class="type">&lt;string&gt;</span> Specifies the filename used in stack traces produced
by this script.</li>
<li><code>lineOffset</code> <span class="type">&lt;number&gt;</span> Specifies the line number offset that is displayed
in stack traces produced by this script.</li>
<li><code>columnOffset</code> <span class="type">&lt;number&gt;</span> Specifies the column number offset that is displayed
in stack traces produced by this script.</li>
<li><code>displayErrors</code> <span class="type">&lt;boolean&gt;</span> When <code>true</code>, if an <a href="errors.html#errors_class_error"><code>Error</code></a> error occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace.</li>
<li><code>timeout</code> <span class="type">&lt;number&gt;</span> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a>
will be thrown.</li>
</ul>
</li>
</ul>
<p><code>vm.runInThisContext()</code> compiles <code>code</code>, runs it within the context of the
current <code>global</code> and returns the result. Running code does not have access to
local scope, but does have access to the current <code>global</code> object.</p>
<p>The following example illustrates using both <code>vm.runInThisContext()</code> and
the JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> function to run the same code:</p>
<pre><code class="lang-js">const vm = require(&#39;vm&#39;);
var localVar = &#39;initial value&#39;;

const vmResult = vm.runInThisContext(&#39;localVar = &quot;vm&quot;;&#39;);
console.log(&#39;vmResult:&#39;, vmResult);
console.log(&#39;localVar:&#39;, localVar);

const evalResult = eval(&#39;localVar = &quot;eval&quot;;&#39;);
console.log(&#39;evalResult:&#39;, evalResult);
console.log(&#39;localVar:&#39;, localVar);

// vmResult: &#39;vm&#39;, localVar: &#39;initial value&#39;
// evalResult: &#39;eval&#39;, localVar: &#39;eval&#39;
</code></pre>
<p>Because <code>vm.runInThisContext()</code> does not have access to the local scope,
<code>localVar</code> is unchanged. In contrast, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> <em>does</em> have access to the
local scope, so the value <code>localVar</code> is changed. In this way
<code>vm.runInThisContext()</code> is much like an <a href="https://es5.github.io/#x10.4.2">indirect <code>eval()</code> call</a>, e.g.
<code>(0,eval)(&#39;code&#39;)</code>.</p>
<h2>Example: Running an HTTP Server within a VM<span><a class="mark" href="#vm_example_running_an_http_server_within_a_vm" id="vm_example_running_an_http_server_within_a_vm">#</a></span></h2>
<p>When using either <a href="#vm_script_runinthiscontext_options"><code>script.runInThisContext()</code></a> or <a href="#vm_vm_runinthiscontext_code_options"><code>vm.runInThisContext()</code></a>, the
code is executed within the current V8 global context. The code passed
to this VM context will have its own isolated scope.</p>
<p>In order to run a simple web server using the <code>http</code> module the code passed to
the context must either call <code>require(&#39;http&#39;)</code> on its own, or have a reference
to the <code>http</code> module passed to it. For instance:</p>
<pre><code class="lang-js">&#39;use strict&#39;;
const vm = require(&#39;vm&#39;);

let code =
`(function(require) {

   const http = require(&#39;http&#39;);

   http.createServer( (request, response) =&gt; {
     response.writeHead(200, {&#39;Content-Type&#39;: &#39;text/plain&#39;});
     response.end(&#39;Hello World\\n&#39;);
   }).listen(8124);

   console.log(&#39;Server running at http://127.0.0.1:8124/&#39;);
 })`;

 vm.runInThisContext(code)(require);
</code></pre>
<p><em>Note</em>: The <code>require()</code> in the above case shares the state with context it is
passed from. This may introduce risks when untrusted code is executed, e.g.
altering objects from the calling thread&#39;s context in unwanted ways.</p>
<h2>What does it mean to &quot;contextify&quot; an object?<span><a class="mark" href="#vm_what_does_it_mean_to_contextify_an_object" id="vm_what_does_it_mean_to_contextify_an_object">#</a></span></h2>
<p>All JavaScript executed within Node.js runs within the scope of a &quot;context&quot;.
According to the <a href="https://developers.google.com/v8/embed#contexts">V8 Embedder&#39;s Guide</a>:</p>
<blockquote>
<p>In V8, a context is an execution environment that allows separate, unrelated,
JavaScript applications to run in a single instance of V8. You must explicitly
specify the context in which you want any JavaScript code to be run.</p>
</blockquote>
<p>When the method <code>vm.createContext()</code> is called, the <code>sandbox</code> object that is
passed in (or a newly created object if <code>sandbox</code> is <code>undefined</code>) is associated
internally with a new instance of a V8 Context. This V8 Context provides the
<code>code</code> run using the <code>vm</code> modules methods with an isolated global environment
within which it can operate. The process of creating the V8 Context and
associating it with the <code>sandbox</code> object is what this document refers to as
&quot;contextifying&quot; the <code>sandbox</code>.</p>

      </div>
    </div>
  </div>
  <script src="assets/sh_main.js"></script>
  <script src="assets/sh_javascript.min.js"></script>
  <script>highlight(undefined, undefined, 'pre');</script>
</body>
</html>

